package com.ly.erms.modular.system.controller;

import static com.ly.erms.core.support.HttpKit.getIp;

import java.util.List;

import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.google.code.kaptcha.Constants;
import com.ly.erms.common.exception.InvalidKaptchaException;
import com.ly.erms.common.persistence.dao.UserMapper;
import com.ly.erms.common.persistence.model.User;
import com.ly.erms.core.base.controller.BaseController;
import com.ly.erms.core.log.LogManager;
import com.ly.erms.core.log.factory.LogTaskFactory;
import com.ly.erms.core.node.MenuNode;
import com.ly.erms.core.shiro.ShiroKit;
import com.ly.erms.core.shiro.ShiroUser;
import com.ly.erms.core.util.KaptchaUtil;
import com.ly.erms.core.util.ToolUtil;
import com.ly.erms.modular.system.dao.MenuDao;

/**
 * 登陆控制器
 * 
 * @author liuyang
 * @date 2017年12月28日
 */
@Controller
public class LoginController extends BaseController {
	
	@Autowired
	MenuDao menuDao;
	
	@Autowired
	UserMapper userMapper;
	
	/**
	 * 跳转到主页
	 */
	@RequestMapping(value="/",method=RequestMethod.GET)
	public String index(Model model){
		//获取菜单列表
		List<Integer> roleList = ShiroKit.getUser().getRoleList();
		if(roleList ==null || roleList.size() ==0){
			ShiroKit.getSubject().logout();
			model.addAttribute("tips", "该用户没有角色，无法登陆");
			return "/login.html";
		}
		List<MenuNode> menus = menuDao.getMenusByRoleIds(roleList);
		List<MenuNode> titles = MenuNode.buildTitle(menus);
	//	titles = ApiMenuFilter.build(titles);
		model.addAttribute("titles", titles);
		
		//获取用户头像
		Integer id = ShiroKit.getUser().getId();
		User user = userMapper.selectById(id);
		String avatar = user.getAvatar();
		model.addAttribute("avatar",avatar);
		
		return "/index.html";
	}
	
	 /**
     * 跳转到登录页面
     */
    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public String login() {
        if (ShiroKit.isAuthenticated() || ShiroKit.getUser() != null) {
            return REDIRECT + "/";
        } else {
            return "/login.html";
        }
    }
	
	/**
	 * 点击登陆执行的动作
	 * 
	 * @return
	 */
	@RequestMapping(value = "/login", method = RequestMethod.POST)
	public String loginVali() {
		String username = super.getPara("username").trim();
		String password = super.getPara("password").trim();
		String remember = super.getPara("remember");

		// 验证验证码是否正确
		if (KaptchaUtil.getKaptchaOnOff()) {
			String kaptcha = super.getPara("kaptcha").trim();
			String code = (String) super.getSession().getAttribute(Constants.KAPTCHA_SESSION_KEY);
			if (ToolUtil.isEmpty(kaptcha) || !kaptcha.equalsIgnoreCase(code)) {
				throw new InvalidKaptchaException();
			}
		}
		Subject currentUser = ShiroKit.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(username,password.toCharArray());
		if("on".equals(remember)){
			token.setRememberMe(true);
		}else{
			token.setRememberMe(false);
		}
		currentUser.login(token);
		ShiroUser user = ShiroKit.getUser();
		super.getSession().setAttribute("shiroUser",user);
		super.getSession().setAttribute("username", user.getAccount());
		
		LogManager.me().executeLog(LogTaskFactory.loginLog(user.getId(), getIp()));
		ShiroKit.getSession().setAttribute("sessionFlag", true);
		return REDIRECT+"/";
	}
	
	/**
	 * 退出登录
	 */
	@RequestMapping("/logout")
	public String logOut(){
		LogManager.me().executeLog(LogTaskFactory.exitLog(ShiroKit.getUser().getId(), getIp()));
		ShiroKit.getSubject().logout();
		return REDIRECT +"/login";
	}
}
